package shining365.programmableweb.data.collect;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import shining365.programmableweb.data.model.Api;
import shining365.programmableweb.data.model.Mashup;


@Transactional
public class Dao {
	public static Dao getInstance() {
		return dao;
	}
	
    @PersistenceContext
    public void setEm(EntityManager em) {
    	logger.debug("@PersistenceContext injected: " + em);
    	this.em = em;
    }

    public void merge(Mashup mashup) {
    	em.merge(mashup);
    }

	public Mashup findMashup(String name) {
		Mashup mashup = em.find(Mashup.class, name);
		if (mashup != null) {
			mashup.toString();
		}
    	return mashup;
    }

    @SuppressWarnings("unchecked")
	public List<Mashup> findAllMashups() {
    	Query q = em.createQuery("select m from " + Mashup.class.getName() + " m");
    	List<Mashup> l = q.getResultList();
    	//初始化
    	for (Mashup m : l) {
    		m.toString();
    	}
    	return l;
    }

    @SuppressWarnings("unchecked")
	public List<Api> findAllApis() {
    	Query q = em.createQuery("select a from " + Api.class.getName() + " a");
    	List<Api> l = q.getResultList();
    	//初始化
    	for (Api s : l) {
    		s.toString();
    	}
    	return l;
    }

    /**不要实例化Dao, 而是调用{@link #getInstance()}
     * 这个函数只被spring调用一次*/
    @Deprecated
    public Dao() {}

    private static Logger logger = Logger.getLogger(Dao.class);
	private EntityManager em;
	private static Dao dao;

	static {
		try {
			ClassPathXmlApplicationContext context = 
				new ClassPathXmlApplicationContext("/applicationContext.xml");
			dao = (Dao)context.getBean("dao");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
